package edu.henu.personnel.controller;

import edu.henu.personnel.entity.User;
import edu.henu.personnel.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @program: personnel
 * @description: 用户登录控制器
 * @author: zhuyang
 * @create: 2019-04-24 16:17
 */

@Slf4j
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String toLoginPage() {
        System.out.println("to login page");
        return "login";
    }

    @PostMapping(value = "/login")
    public String userLogin(@RequestParam("username") String username,
                            @RequestParam("password") String password,
                            Map<String,Object> map, HttpSession session) {
        System.out.println("进入登录控制器");
        if (username == null || password == null) {
            map.put("msg", "登录信息存在空");
            return "login";
        }
        User loginUser = userService.login(username, password);
        if (loginUser == null) {
            // 登录失败
            map.put("msg", "用户名或密码错误");
            return "login";
        } else {
            // 登录成功
            session.setAttribute("loginUser", loginUser);

            return "redirect:/dashboard.html";
        }
    }

    @GetMapping(value = "/loginOut")
    public String loginOut(Model model) {
        model.addAttribute("outResult", "成功退出");
        return "login";
    }
}
